using Universal.Application.Contracts.Common;
using Universal.Application.Contracts.Dto.User;
using Universal.Application.Contracts.Storage;
using Universal.Application.Repositories;
using Universal.Domain.Entities.App;
using Universal.Domain.Repositories;

namespace Universal.Application.Services;

/// <summary>
/// 文件服务实现类
/// </summary>
public class FileService : IFileService
{

    private readonly IRepository<AppFile> _fileRepository;
    private readonly IFileStorage _fileStorage;
    private readonly IRepository<AppUser> _userRepository;
    private readonly ILogService _logService;

    public FileService(IRepository<AppFile> fileRepository, ILogService logService, IFileStorage fileStorage, IRepository<AppUser> userRepository)
    {
        _fileRepository = fileRepository;
        _fileStorage = fileStorage;
        _userRepository = userRepository;
        _logService = logService;
    }

    // 下载文件
    public Task<(Stream fileStream, string mimeType, string originalName)> DownloadAsync(Guid fileId)
    {
        throw new NotImplementedException();
    }

    // 上传文件
    public Task<AppFile> UploadAsync(Stream fileStream, string originalName, string mimeType, long size, Guid userId)
    {
        throw new NotImplementedException();
    }

    // 上传头像
    public async Task<dynamic> UploadAvatarAsync(UploadAvatarDto dto)
    {
        try
        {
            var file = dto.File;
            var allowedTypes = new[] { ".jpg", ".jpeg", ".png", ".gif" };
            var ext = Path.GetExtension(file.FileName).ToLower();
            if (!allowedTypes.Contains(ext))
            {
                return ApiResponse<string>.Failure(400, "只允许上传图片文件");
            }

            if (file.Length > 2 * 1024 * 1024)
            {
                return ApiResponse<string>.Failure(400, "图片大小不能超过2MB");
            }

            // 验证用户ID
            if (string.IsNullOrEmpty(dto.UserId) || !Guid.TryParse(dto.UserId, out var userId))
            {
                return ApiResponse<string>.Failure(400, "用户ID无效");
            }

            var fileName = Guid.NewGuid() + ext;
            var url = await _fileStorage.SaveFileAsync(file.OpenReadStream(), fileName);

            var appFile = new AppFile
            {
                Filename = fileName,
                OriginalName = file.FileName,
                Path = url,
                Size = file.Length,
                MimeType = file.ContentType,
                UserId = userId
            };
            await _fileRepository.AddAsync(appFile);

            // 新增：更新用户头像
            var user = await _userRepository.GetByIdAsync(userId);
            if (user != null)
            {
                user.Avatar = url;
                await _userRepository.UpdateAsync(user);
                await _logService.WriteLogAsync($"用户{user.Username}更新头像成功");
            }

            return ApiResponse<string>.Success(url, "上传成功");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex); // 打印详细异常
            return ApiResponse<string>.Failure(500, "服务器内部错误: " + ex.Message);
        }
    }
}